//
//  HLUserDetailViewController.m
//  YueYue
//
//  Created by hulu001 on 2023/5/18.
//

#import "HLUserDetailViewController.h"

#import "HLUserDetailHeaderView.h"
#import "HLUserDetailBottomView.h"
#import "HLUserDetailCell.h"

#import "HLEditInfoViewController.h"
#import "HLReportViewController.h"
#import "HLUserVideoListRequest.h"
#import "HLUserInfoRequest.h"
#import "HLUserOptionRequest.h"

@interface HLUserDetailViewController ()<UIScrollViewDelegate>
@property (nonatomic, strong) HLUserInfoModel *user;
@property (nonatomic, strong) UIImage *barBackImage;
@property (nonatomic, strong) UIColor *barItemColor;
@property (nonatomic, assign) UIStatusBarStyle statusStyle;

@property (nonatomic, strong) HLUserDetailBottomView *bottomView;
@property (nonatomic, strong) NSString *userId;

@property (nonatomic, strong) HLUserInfoRequest *userInfoRequest;

@property (nonatomic, copy) HLCommonCallback meCallback;
@property (nonatomic, assign) BOOL isMe;

@end

@implementation HLUserDetailViewController


- (instancetype)initWithUserId:(nonnull NSString *)userId
{
    self = [super initWithStyle:UITableViewStyleGrouped];
    if(self){
        self.userId = userId;
    }
    return self;
}

- (instancetype)initMeWithCallback:(HLCommonCallback)callback
{
    self = [super initWithStyle:UITableViewStyleGrouped];
    if(self){
        self.userId = nil;
        self.meCallback = callback;
        self.isMe = YES;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = HLBackgroundColor;
    self.barBackImage = [UIImage qmui_imageWithColor:UIColorClear];
    self.barItemColor = UIColorWhite;
    self.statusStyle = UIStatusBarStyleLightContent;
    if (_isMe){
        self.request = [[HLUserVideoListRequest alloc] initWithMe];
        self.userInfoRequest = [[HLUserInfoRequest alloc] initWithMe];
    } else {
        self.request = [[HLUserVideoListRequest alloc] initWithUserId:_userId];
        self.userInfoRequest = [[HLUserInfoRequest alloc] initWithUserId:_userId];
    }

    self.request.delegate = self;
    [self.request start];
    [self requestUserInfo];
    [self showEmptyView];
    [self.emptyView setTextLabelText:@"加载中..."];
    [self.emptyView.loadingView startAnimating];
}

- (void)requestUserInfo
{
    [self.userInfoRequest startWithCompletionBlockWithSuccess:^(__kindof HLUserInfoRequest * _Nonnull request) {
        if(request.isSuccess){
            self.user = [request user];
            self.bottomView.model = self.user;
            self.bottomView.hidden = NO;
            if (![HLRunTime shareInstance].isFood) {
                [self.bottomView.editButton addTarget:self action:@selector(editAction) forControlEvents:UIControlEventTouchUpInside];
            }
            MJWeakSelf
            [self.kvoController observe:self.user keyPath:@"chatUp" options:NSKeyValueObservingOptionNew block:^(id  _Nullable observer, id  _Nonnull object, NSDictionary<NSString *,id> * _Nonnull change) {
                NSString *changeString = change[NSKeyValueChangeNewKey];
                if ([changeString isEqualToString:@"1"]){
                    weakSelf.homeModel.chatUp = changeString;
                }
            }];
            
            [self.kvoController observe:self.user keyPath:@"nickName" options:NSKeyValueObservingOptionNew block:^(id  _Nullable observer, id  _Nonnull object, NSDictionary<NSString *,id> * _Nonnull change) {
                if (weakSelf.meCallback){
                    weakSelf.meCallback(object);
                }
            }];
            [self userBlackRequest];
            [self.tableView reloadData];
        } else if ([request.code isEqualToString:@"1003"]){
            [self.navigationController popViewControllerAnimated:YES];
        }
    } failure:nil];
}

- (void)userBlackRequest
{
    HLUserOptionRequest *relationRequest = [[HLUserOptionRequest alloc] initWithType:HLUserOptionTypeRelationship params:@{@"othersId":self.user.userId}];
    [relationRequest startWithCompletionBlockWithSuccess:^(__kindof HLUserOptionRequest * _Nonnull request) {
        if (request.isSuccess){
            if ([request.result[@"data"] isKindOfClass:[NSString class]]){
                self.user.isBlacklist = [request.result[@"data"] isEqualToString:@"2"] ? @"1": @"0";
            } else {
                self.user.isBlacklist = @"0";
            }
        }
    } failure:nil];
}

- (void)setupNavigationItems
{
    [super setupNavigationItems];

    if (_isMe){
        self.title = @"我的主页";
    } else {
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:UIImageMake(@"nav_more") style:UIBarButtonItemStylePlain target:self action:@selector(moreAction)];
    }
}


- (void)initTableView
{
    [super initTableView];
    
    self.bottomView = [[HLUserDetailBottomView alloc] init];
    [self.view addSubview:_bottomView];
    [_bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.left.right.mas_equalTo(0);
    }];

    self.bottomView.hidden = YES;
    [self.tableView registerClass:[HLUserDetailCell class] forCellReuseIdentifier:[HLUserDetailCell identifyCell]];
    [self.tableView registerClass:[HLUserDetailHeaderView class] forHeaderFooterViewReuseIdentifier:[HLUserDetailHeaderView identifyCell]];
    
}

- (void)layoutTableView
{
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.top.mas_equalTo(-(NavigationContentTop));
        make.bottom.mas_equalTo(-(SafeAreaInsetsConstantForDeviceWithNotch.bottom + 40));
    }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.datasources.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    HLUserDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:[HLUserDetailCell identifyCell]];
    if (self.datasources.count <= indexPath.row){
        return cell;
    }
    cell.model = self.datasources[indexPath.row];
    return cell;
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    
    HLUserDetailHeaderView *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:[HLUserDetailHeaderView identifyCell]];
    headerView.model = self.user;
    return headerView;
}


- (void)headerRefresh
{
    [self.kvoController unobserveAll];
    HLUserVideoListRequest *videoRequest = (HLUserVideoListRequest *)self.request;
    videoRequest.page = 1;
    [self.request start];
    [self requestUserInfo];
}

- (void)footerRefresh
{
    HLUserVideoListRequest *videoRequest = (HLUserVideoListRequest *)self.request;
    videoRequest.page += 1;
    [self.request start];
}

- (void)requestFinished:(__kindof YTKBaseRequest *)request
{
    [super requestFinished:request];
    
    HLUserVideoListRequest *videoRequest = (HLUserVideoListRequest *)request;
    if (videoRequest.page == 1){
        [self.datasources removeAllObjects];
    }
    
    NSArray *videoList = [videoRequest videoList];
    
    [self.datasources addObjectsFromArray:videoList];
    
    if (videoList.count < [HLListPageSize integerValue] && self.datasources.count > 0){
        [self noMordDataWithFooterRefresh];
    }
    
    if (self.datasources.count == 0 && videoRequest.page == 1 && !self.isMe){
        [self.emptyView setLoadingViewHidden:YES];
        [self.emptyView setImage:UIImageMake(@"empty_icon_3")];
        [self.emptyView setTextLabelText:@"暂时没有动态，快去提醒她发一个吧"];
        self.emptyView.verticalOffset = -220;
        self.emptyView.textLabelInsets = UIEdgeInsetsMake(-40, 0, 0, 0);
        self.emptyView.qmui_height = 300;
        self.tableView.tableFooterView = self.emptyView;
    } else {
        [self hideEmptyView];
    }
    
    [self.tableView reloadData];
}

- (void)requestFailed:(__kindof YTKBaseRequest *)request
{
    [super requestFailed:request];
    [self.emptyView setLoadingViewHidden:YES];
    [self.emptyView setImage:UIImageMake(@"empty_icon_2")];
    [self.emptyView setTextLabelText:request.error.localizedDescription];
}

- (UIImage *)qmui_navigationBarBackgroundImage
{
    return self.barBackImage;
}

- (nullable UIColor *)qmui_navigationBarTintColor
{
    return self.barItemColor;
}

- (nullable UIColor *)qmui_titleViewTintColor
{
    return self.barItemColor;
}

- (UIStatusBarStyle)preferredStatusBarStyle
{
    return self.statusStyle;
}

- (BOOL)shouldPopViewControllerByBackButtonOrPopGesture:(BOOL)byPopGesture
{
    [[NSNotificationCenter defaultCenter] postNotificationName:HLUserDetailScrollDidChangeNotification object:nil];
    return YES;
}
- (BOOL)forceEnableInteractivePopGestureRecognizer
{
    return NO;
}


- (void)editAction
{
    MJWeakSelf
    HLEditInfoViewController *editInfoVC = [[HLEditInfoViewController alloc] initWithModel:self.user callback:^(HLUserInfoModel *user) {
        [weakSelf.request start];
        [weakSelf requestUserInfo];
    }];
    [self.navigationController pushViewController:editInfoVC animated:YES];
}


- (void)moreAction
{
    NSString *blackContent = @"拉黑该用户";
    NSString *blackTitle = @"拉黑";
    BOOL hasBlack = [_user.isBlacklist boolValue];
    if (hasBlack){
        blackContent = @"将该用户移出黑名单";
        blackTitle = @"移出黑名单";
    }
    
    QMUIAlertAction *actionCancel = [QMUIAlertAction actionWithTitle:@"取消" style:QMUIAlertActionStyleCancel handler:^(QMUIAlertController *aAlertController, QMUIAlertAction *action) {
    }];
    QMUIAlertAction *actionReport = [QMUIAlertAction actionWithTitle:@"举报" style:QMUIAlertActionStyleDefault handler:^(QMUIAlertController *aAlertController, QMUIAlertAction *action) {
        HLReportViewController *reportVC = [[HLReportViewController alloc] initWithType:HLReportTypeMine userId:self.userId];
        [self.navigationController pushViewController:reportVC animated:YES];
    }];
    MJWeakSelf;
    QMUIAlertAction *actionBlack = [QMUIAlertAction actionWithTitle:blackTitle style:QMUIAlertActionStyleDefault handler:^(QMUIAlertController *aAlertController, QMUIAlertAction *action) {
        [HLUIHelper blackWithUserId:weakSelf.user.userId black:hasBlack callback:^(BOOL isConfirm) {
            if (isConfirm){
                weakSelf.user.isBlacklist = hasBlack ? @"0" : @"1";
            }
        }];
    }];

    QMUIAlertController *alertController = [QMUIAlertController alertControllerWithTitle:@"" message:@"" preferredStyle:QMUIAlertControllerStyleActionSheet];
    alertController.sheetButtonAttributes = @{NSForegroundColorAttributeName:HLTextColor1,NSFontAttributeName:UIFontMediumMake(16)};
    alertController.sheetCancelButtonAttributes = @{NSForegroundColorAttributeName:HLTextColor2,NSFontAttributeName:UIFontMediumMake(16)};
    [alertController addAction:actionCancel];
    [alertController addAction:actionReport];
    [alertController addAction:actionBlack];
    [alertController showWithAnimated:YES];
}

#pragma mark UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    
//    if (scrollView.contentOffset.y < 0) {
//            scrollView.contentOffset = CGPointMake(0, 0);
//    }
//
//    [[NSNotificationCenter defaultCenter] postNotificationName:HLUserDetailScrollDidChangeNotification object:nil];
//    self.barBackImage = [UIImage qmui_imageWithColor:UIColorClear];
//    self.barItemColor = UIColorWhite;
//    self.statusStyle = UIStatusBarStyleLightContent;
//    self.title = _isMe? @"我的主页": @"";
//    if (scrollView.contentOffset.y < 0) {
//        scrollView.contentOffset = CGPointMake(0, 0);
//    } else if (scrollView.contentOffset.y > 80){
//        self.barBackImage = [UIImage qmui_imageWithColor:UIColorWhite];
//        self.barItemColor = UIColorBlack;
//        self.statusStyle = UIStatusBarStyleDarkContent;
//        self.title = _isMe? @"我的主页" : @"用户详情";
//    }
//    [self updateNavigationBarAppearance];
}

@end
